package de.dhbw.karlsruhe.picsim.util.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.*;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: May 1, 2010
 * Time: 11:43:08 PM
 */

/**
 * Logt Fehlermeldungen die beim ausführen über Executoren entstehen
 */
public final class LoggingExecutor extends ThreadPoolExecutor {
    private static final Log log = LogFactory.getLog(LoggingExecutor.class);

    public LoggingExecutor() {
        super(1, 1, 0L, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>());

    }

    @Override
    protected void afterExecute(final Runnable r, final Throwable t) {
        super.afterExecute(r, t);

        if (r instanceof Future) {
            final Future task = (Future) r;
            try {
                final Object o = task.get();
                log.debug(o);
            } catch (InterruptedException e) {
                log.error(e);
            } catch (ExecutionException e) {
                final Throwable cause = e.getCause();
                logException(r, cause);
            }

        } else if (t != null) {
            logException(r, t);
        }
    }

    private void logException(final Runnable r, final Throwable cause) {
        log.error("Exception in task " + r, cause);
        LoggingExceptionHandler.showErrorWindow(cause);

    }
}
